package com.hotel.BL;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.EntityName;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.CompositeFilterOperator;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.FilterPredicate;
import com.google.appengine.api.datastore.Query.SortDirection;

import data.Charge;
import data.Folio;
import data.Group;
import data.Reservation;
import data.SubPayment;
import data.passingData.FolioData;


public class FolioLogic extends AbstractBL{
	
	
//	public FolioLogic()
//	{
//		
//	}
//	
	public FolioLogic(HttpServletRequest req, HttpServletResponse resp)
	{
		this.req = req;
		this.resp= resp;
	}
	public Folio GetFolio(long id)
	{
		Key key = KeyFactory.createKey(EntityName.Folio, id);
		try {
			Entity lang = datastore.get(key);
			Folio c = new Folio();
			c.setEntity(lang);
			return c;
		} catch (EntityNotFoundException e) {
			return null;
		}
	}
			
	public List<Folio> GetAllFolio(long hotelId)
	{
		Query q = new Query(EntityName.Folio);
		
		Filter filterHotel = new FilterPredicate("hotelId",FilterOperator.EQUAL,hotelId);
		Filter filterStatus = new FilterPredicate("status",FilterOperator.EQUAL,"true");
		Filter filterAvaliable = new FilterPredicate("avaliable",FilterOperator.EQUAL,"true");

		Filter filter = CompositeFilterOperator.and(filterHotel, filterStatus, filterAvaliable);
		q.setFilter(filter);
		
		return GetList(datastore.prepare(q).asList(FetchOptions.Builder.withDefaults()));
	}
	
	public Folio GetFolio(Entity entity)
	{
		Folio item = new Folio();
		item.setEntity(entity);
		return item;
	}
	
	public List<Folio> GetList(List<Entity> entities)
	{
		List<Folio> list = new ArrayList<Folio>();
		for(Entity e : entities)
		{
			Folio a = new Folio();
			a.setEntity(e);
			list.add(a);
		}
		return list;
	}

	public List<FolioData> AddFolio(long hotelId,String chargeRes,String resId,boolean isLock,String chargeGroup,String chargeGroupId) throws EntityNotFoundException
	{
		
		List<FolioData> list = new ArrayList<FolioData>();
		String [] n=resId.split(",");
		String [] chsrgeresItem =chargeRes.split(","); 
		ChargeLogic chargeLogic = new ChargeLogic(req,resp);
		if(chargeRes!=null|| chargeGroup!=null)
		{
				if(chargeRes !=null)
				{
					for(int i =0;i<n.length;i++)
					{
						if(!n[i].equals("")){
						Folio b = new Folio();
					
						String [] Arrayofcharge = chsrgeresItem[i].split("_");
						StringBuffer result = new StringBuffer();
						for(int  u= 0;u<Arrayofcharge.length;u++)
						{
							if(u == (Arrayofcharge.length-1))
							{
								result.append( Arrayofcharge[u] );
							}else
							{
								result.append( Arrayofcharge[u]+"," );
							}
						}
						String mynewstring = result.toString();
						b.setChargeString(String.valueOf(mynewstring));
						b.setDisplayId(GetMaxFolioDisplayId(hotelId)+1);
						b.setHotelId(hotelId);
						b.setLock(isLock);

						Key k = datastore.put(b.getEntity());
						b.setId(k.getId());
						b.setKey(k);						
					
						Reservation res = new ReservationLogic(req,resp).GetReservation(Long.parseLong(n[i]));
						if(res.getFolioListString() != null)
						{
							res.setFolioListString(res.getFolioListString()+","+String.valueOf(b.getId()));	
						}
						else
						{
							res.setFolioListString(String.valueOf(b.getId()));
						}
						Key kk = datastore.put(res.getEntity());
						res.setId(kk.getId());
						res.setKey(kk);
						
						
						FolioData  fd = new FolioData();
							fd.setRoomType(res.getRoomType().getShortName());
							fd.setRoomName(res.getRoom().getRoomName());
							fd.setFolioId(res.getFolioListString());
						if(!res.getGuestString().equals("0")){
							fd.setGuestName(res.getGuest().getFirstName()+" "+res.getGuest().getLastName());
							fd.setGuestId(String.valueOf(res.getGuest().getId()));
						}
							String allChargeInres =res.getChargeListString();
							if(res.getOtherChargeString()!=null&&!res.getOtherChargeString().equals("")){
								allChargeInres+=","+res.getOtherChargeString();
							}
							String [] chargeId =allChargeInres.split(",");
							for(int m =0;m<chargeId.length;m++)
							{
								Charge ch = chargeLogic.GetCharge(Long.parseLong(chargeId[m]));
								if(ch.isTemp() != true)
								{
									fd.setMoney(ch.getChargeAmount());
									ch.setSubFolio(b.getId()+"_"+m);
									ch.setFolioId(b.getId());
									Key kc = datastore.put(ch.getEntity());
									ch.setId(kc.getId());
									ch.setKey(kc);
								}
							}
							
							fd.setPaid("0");
							fd.setLock(b.isLock());
							list.add(fd);
					}
						}
			}

				if(!chargeGroupId.equals("0"))
				{
					
				Folio b = new Folio();
				
				if(chargeGroup != null)
				{
					b.setChargeString(chargeGroup);
				}
				
				b.setHotelId(hotelId);
				b.setLock(isLock);
				
				
				Key k = datastore.put(b.getEntity());
				b.setId(k.getId());
				b.setKey(k);
				
				Group g= new ReservationLogic(req,resp).GetGroup(Long.parseLong(chargeGroupId));
					
				if(g.getFolioListString() != null)
				{
					g.setFolioListString(g.getFolioListString()+","+b.getId());
				}else
				{
					g.setFolioListString(String.valueOf(b.getId()));
				}
					
					Key kk = datastore.put(g.getEntity());
					g.setId(kk.getId());
					g.setKey(kk);
				
					FolioData  fdt = new FolioData();

					fdt.setFolioId(g.getFolioListString());
					fdt.setGuestName(g.getGuest().getFirstName()+" "+g.getGuest().getLastName());
					fdt.setGuestId(String.valueOf(g.getGuest().getId()));
					String [] fch =b.getChargeString().split(",");
					
					Charge ch = new Charge();
					double amount = 0;
					for(int t=0;t<fch.length;t++)
					{
						 ch = chargeLogic.GetCharge(Long.parseLong(fch[t].trim()));
					if(ch.isTemp() != true)
					{
						amount+=ch.getChargeAmount();
						ch.setSubFolio(b.getId()+"_"+t);
						ch.setFolioId(b.getId());
						Key kc = datastore.put(ch.getEntity());
						ch.setId(kc.getId());
						ch.setKey(kc);
					}
					
					}
					fdt.setMoney(amount);
					fdt.setPaid("0");
					fdt.setLock(b.isLock());
					list.add(fdt);
				}
				else if(chargeGroupId.equals("0"))
				{
					list.add(null);
				}
				
			}
		return list;
	}
	
	



	public List<List< ArrayList<FolioData>> > LoadFolioList(String groupId) throws EntityNotFoundException
	{
		List< List< ArrayList<FolioData>> > Addlist = new ArrayList<List< ArrayList<FolioData>> >();
		ReservationLogic resLogic = new ReservationLogic(req,resp);
		FolioLogic folioLogic = new FolioLogic(req,resp);
		ChargeLogic chargeLogic = new ChargeLogic(req,resp);
		SubPaymentLogic subPaymentLogic = new SubPaymentLogic(req,resp);
		
		if(groupId != null && groupId != "0"){
		Group g= resLogic.GetGroup(Long.parseLong(groupId));
		String resId = g.getListResvString();
		String[] n =resId.split(",");
		
		if(g.getFolioListString() != null )
		{
			
			List< ArrayList<FolioData>> list = new ArrayList<ArrayList<FolioData>>();			
			ArrayList<FolioData> sublist = new ArrayList<FolioData>();
			ArrayList<FolioData> sublistt = new ArrayList<FolioData>();
			FolioData  fd = new FolioData();
			FolioData  fdsub = new FolioData();
			String[] gFolioLisrt =g.getFolioListString().split(",");
	
			for(int gg =0;gg<gFolioLisrt.length;gg++)
			{
			
				fd.setRoomName("owner");
			
				String [] gFId = g.getFolioListString().split(",");
				for(int y=0;y<gFId.length;y++){
					  fdsub = new FolioData();
					  fdsub.setRoomName("owner");
					  fdsub.setgId(String.valueOf(g.getId()));
						fdsub.setGuestName(g.getGuest().getFirstName()+" "+g.getGuest().getLastName());
						fdsub.setGuestId(String.valueOf(g.getGuest().getId()));
						
					Folio b = folioLogic.GetFolio(Long.parseLong(gFId[y].trim()));
					fdsub.setFolioId(String.valueOf(b.getId()));
					fdsub.setLock(b.isLock());
					
					
					
					double sumChargeAmount=0;
					double sumPaymentAmount=0;
					
					String [] chIdArray = b.getChargeString().trim().split(",");
					
					for(int nn=0;nn<chIdArray.length;nn++)
					{
						Charge ch = chargeLogic.GetCharge(Long.parseLong(chIdArray[nn]));
							sumChargeAmount+=ch.getChargeAmount();
						if(b.getPaymentString()==null)
						{
							fdsub.setPaid("0");
							fdsub.setBalance(ch.getChargeAmount());
						}
					}
					if(b.getPaymentString()!= null)
					{
						String [] pmIdArray = b.getPaymentString().trim().split(",");
						for(int pmn=0;pmn<pmIdArray.length;pmn++)
						{
						SubPayment pm = subPaymentLogic.GetSubPayment(Long.parseLong(pmIdArray[pmn]));
						System.out.println("pm.getAmount()="+pm.getAmount());
						
						sumPaymentAmount+=pm.getAmount();
						fdsub.setPaid(String.valueOf(sumPaymentAmount));
						}
					}
						
						
					fdsub.setMoney(sumChargeAmount);
					fdsub.setBalance(sumChargeAmount-sumPaymentAmount);
			
					sublistt.add(fdsub);
					
				}
				list.add( sublistt);
				sublist.add(fd);
				list.add( sublist);
				Addlist.add(list);
				
				
			}
		}
		
		for(int i =0;i<n.length;i++)
		{
			List< ArrayList<FolioData>> list = new ArrayList<ArrayList<FolioData>>();
			
			ArrayList<FolioData> sublist = new ArrayList<FolioData>();
			ArrayList<FolioData> sublistt = new ArrayList<FolioData>();
			
			FolioData  fd = new FolioData();
			FolioData  fdsub = new FolioData();
			long idNumber =Long.parseLong(n[i].trim());
			Reservation res = resLogic.GetReservation(idNumber);
			
			if(res.getFolioListString() != null){
				fd.setRoomType(res.getRoomType().getShortName());
				fd.setRoomName(res.getRoom().getRoomName());
			
				String [] fId = res.getFolioListString().split(",");
				for(int y=0;y<fId.length;y++){
					fdsub = new FolioData();
					fdsub.setRoomType(res.getRoomType().getShortName());
					fdsub.setRoomName(res.getRoom().getRoomName());
					fdsub.setResId(String.valueOf(res.getId()));
					if(!res.getGuestString().equals("0")){
						fdsub.setGuestName(res.getGuest().getFirstName()+" "+res.getGuest().getLastName());
						fdsub.setGuestId(String.valueOf(res.getGuest().getId()));
					}
					Folio b = folioLogic.GetFolio(Long.parseLong(fId[y].trim()));
					fdsub.setFolioId(String.valueOf(b.getId()));
					fdsub.setLock(b.isLock());
					double sumChargeAmount=0;
					double sumPaymentAmount=0;
					String [] chIdArray = b.getChargeString().trim().split(",");
					for(int nn=0;nn<chIdArray.length;nn++)
					{
						if(!chIdArray[nn].trim().equals("")){
							Charge ch = chargeLogic.GetCharge(Long.parseLong(chIdArray[nn]));
								sumChargeAmount+=ch.getChargeAmount();
							if(b.getPaymentString()==null)
							{
								fdsub.setPaid("0");
								fdsub.setBalance(ch.getChargeAmount());
							}
														}
					}
					if(b.getPaymentString()!= null)
					{
						String [] pmIdArray = b.getPaymentString().trim().split(",");
						for(int pmn=0;pmn<pmIdArray.length;pmn++)
						{
							SubPayment pm = subPaymentLogic.GetSubPayment(Long.parseLong(pmIdArray[pmn]));
							System.out.println("pm.getAmount()="+pm.getAmount());
					
							sumPaymentAmount+=pm.getAmount();
							fdsub.setPaid(String.valueOf(sumPaymentAmount));
						}
					}	
					fdsub.setMoney(sumChargeAmount);
					fdsub.setBalance(sumChargeAmount-sumPaymentAmount);
					sublistt.add(fdsub);	
			}
			list.add( sublistt);
			sublist.add(fd);
			list.add( sublist);
			Addlist.add(list);	
	}
	
		}
		
	}
	else
	{
		Addlist = null;
	}
		
	if(Addlist.isEmpty() == true)
	{
		Addlist =null;
	}
	
	return Addlist;
		
	
		
		
	}
	
	public List<List< ArrayList<FolioData>> > LoadSingleFolioList(String resId) throws EntityNotFoundException
	{
		FolioLogic folioLogic = new FolioLogic(req,resp);
		ReservationLogic resLogic = new ReservationLogic(req,resp);
		ChargeLogic chargeLogic = new ChargeLogic(req,resp);
		SubPaymentLogic subPaymentLogic = new SubPaymentLogic(req,resp);
		List< List< ArrayList<FolioData>> > Addlist = new ArrayList<List< ArrayList<FolioData>> >();
		List< ArrayList<FolioData>> list = new ArrayList<ArrayList<FolioData>>();
		ArrayList<FolioData> sublist = new ArrayList<FolioData>();
		ArrayList<FolioData> sublistt = new ArrayList<FolioData>();
		FolioData  fd = new FolioData();
		FolioData  fdsub = new FolioData();
		long idNumber =Long.parseLong(resId);
		Reservation res = resLogic.GetReservation(idNumber);
		
if(res.getFolioListString() != null&&!res.getFolioListString().equals("")){

		fd.setRoomType(res.getRoomType().getShortName());
		fd.setRoomName(res.getRoom().getRoomName());
		
		String [] fId = res.getFolioListString().split(",");
		for(int y=0;y<fId.length;y++){
			if(!fId[y].equals("")){
			  fdsub = new FolioData();
			  if(!res.getGroupIdString().equals("0"))
				{
					fdsub.setCheckIngroup(true);
				}else
				{
					fdsub.setCheckIngroup(false);
				}
			  fdsub.setRoomType(res.getRoomType().getShortName());
				fdsub.setRoomName(res.getRoom().getRoomName());
			  fdsub.setResId(String.valueOf(res.getId()));
			if( !res.getGuestString().equals("0")){
				fdsub.setGuestName(res.getGuest().getFirstName()+" "+res.getGuest().getLastName());
				fdsub.setGuestId(String.valueOf(res.getGuest().getId()));
			}
			Folio b = folioLogic.GetFolio(Long.parseLong(fId[y].trim()));
			fdsub.setFolioId(String.valueOf(b.getId()));
			fdsub.setLock(b.isLock());
			
			double sumChargeAmount=0;
			double sumPaymentAmount=0;
			
			String [] chIdArray = b.getChargeString().trim().split(",");
			for(int nn=0;nn<chIdArray.length;nn++)
			{
				if(!chIdArray[nn].trim().equals("")){
					Charge ch = chargeLogic.GetCharge(Long.parseLong(chIdArray[nn]));
						sumChargeAmount+=ch.getChargeAmount();
					if(b.getPaymentString()==null)
					{
						fdsub.setPaid("0");
						fdsub.setBalance(ch.getChargeAmount());
					}
				}
			}
			if(b.getPaymentString()!= null)
			{
				String [] pmIdArray = b.getPaymentString().trim().split(",");
				for(int pmn=0;pmn<pmIdArray.length;pmn++)
				{
				SubPayment pm = subPaymentLogic.GetSubPayment(Long.parseLong(pmIdArray[pmn]));
				System.out.println("pm.getAmount()="+pm.getAmount());
				
				sumPaymentAmount+=pm.getAmount();
				fdsub.setPaid(String.valueOf(sumPaymentAmount));
				}
			}
				
				
			fdsub.setMoney(sumChargeAmount);
			fdsub.setBalance(sumChargeAmount-sumPaymentAmount);
			
				
			
			sublistt.add(fdsub);
		}	
		}
		list.add( sublistt);
		sublist.add(fd);
		list.add( sublist);
		Addlist.add(list);
		}
		else
		{
			Addlist = null;
		}
			return Addlist;
		}
	
	public boolean DeleteFolio(String gid,String resid,String resFolioList,String groupFolioList) throws EntityNotFoundException
	{
		FolioLogic folioLogic = new FolioLogic(req,resp);
		ReservationLogic resLogic = new ReservationLogic(req,resp);
		ChargeLogic chargeLogic = new ChargeLogic(req,resp);
		SubPaymentLogic subPaymentLogic = new SubPaymentLogic(req,resp);
		boolean status = false;
		if(!gid.equalsIgnoreCase("0"))
		{
		//String [] groupIdArray = groupFolioList.split(",");
		Group g= resLogic.GetGroup(Long.parseLong(gid));
		String [] folioGList =g.getFolioListString().trim().split(",");
		String [] folioGListInput =groupFolioList.trim().split(",");
		
		StringBuffer result = new StringBuffer();
		
		for(int i =0;i<folioGListInput.length;i++){
			
			for(int n =0;n<folioGList.length;n++)
				{
			if(!folioGListInput[i].trim().equals(folioGList[n])&& n==(folioGList.length-1)){
				if(result.length() == 0)
				{
						result.append( folioGList[n] );	
				}
				else 
				{
						result.append( ","+folioGList[n]);
					
				}
					}
			else
			{
				break;
			}
			
				}
		
			
			Folio f = folioLogic.GetFolio(Long.parseLong(folioGListInput[i].trim()));
			if(f.getPaymentString() != null && !f.getPaymentString().isEmpty())
			{
				String []subpaymetlist = f.getPaymentString().trim().split(",");
				
				for(int a=0;a<subpaymetlist.length;a++)
				{
					subPaymentLogic.DeleteSubPayment(Long.parseLong(subpaymetlist[a]));
				}
			
			}
			String []chargemetlist = f.getChargeString().trim().split(",");
			for(int a=0;a<chargemetlist.length;a++)
			{
				Charge c = chargeLogic.GetCharge(Long.parseLong(chargemetlist[a]));
				c.setFolioId(0);
				c.setSubFolio(null);
				
				Key kc = datastore.put(c.getEntity());
				c.setId(kc.getId());
				c.setKey(kc);
			}
			
			
			Key key = KeyFactory.createKey(EntityName.Folio, Long.parseLong(folioGListInput[i].trim()));
			datastore.delete(key);
		}
		
		if(result.toString() != null && result.length()!=0)
		{
			g.setFolioListString(result.toString());
		}else
		{
			g.setFolioListString(null);
		}
		
		Key k = datastore.put(g.getEntity());
		g.setId(k.getId());
		g.setKey(k);
		status = true;
		}
		if(resid !="0" && !resid.isEmpty())
		{
			String [] resFolioArray = resFolioList.trim().split(",");
			String [] resIdArray = resid.split(",");
			StringBuffer sum = new StringBuffer();
			
				for(int n = 0;n<resIdArray.length;n++)
				{
					Reservation res = resLogic.GetReservation(Long.parseLong(resIdArray[n]));
					String [] FolioRList ;
					if(res.getFolioListString() != null){
						 FolioRList =res.getFolioListString().trim().split(",");
					}else
					{
						break;
					}
						for(int y = 0;y<resFolioArray.length;y++){
							
						for(int m=0;m<FolioRList.length;m++)
						{
							if(!resFolioArray[y].trim().equals(FolioRList[m])&& m == (FolioRList.length-1) ){
							if(sum.length() == 0)
							{
									sum.append( FolioRList[m] );	
							}
							else
							{
									sum.append(","+FolioRList[m] );	
								
							}
							}else
							{
								break;
							}
						
						}
					
						}

				if(sum.toString() != null && sum.length()!=0)
				{
					res.setFolioListString(sum.toString());
				}
				else
				{
					res.setFolioListString(null);
				}
				
				Key k = datastore.put(res.getEntity());
				res.setId(k.getId());	
				res.setKey(k);
				}
				
				for(int y = 0;y<resFolioArray.length;y++){
					
					Folio f = GetFolio(Long.parseLong(resFolioArray[y].trim()));
					if(f.getPaymentString() != null)
					{
						String []subpaymetlist = f.getPaymentString().trim().split(",");
						
						for(int a=0;a<subpaymetlist.length;a++)
						{
							subPaymentLogic.DeleteSubPayment(Long.parseLong(subpaymetlist[a]));
						}
					
					}
					
					String []chargemetlist = f.getChargeString().trim().split(",");
					for(int a=0;a<chargemetlist.length;a++)
					{
						Charge c = chargeLogic.GetCharge(Long.parseLong(chargemetlist[a]));
						c.setFolioId(0);
						c.setSubFolio(null);
						
						Key kc = datastore.put(c.getEntity());
						c.setId(kc.getId());
						c.setKey(kc);
					}
					
				Key key = KeyFactory.createKey(EntityName.Folio, Long.parseLong(resFolioArray[y].trim()));
				datastore.delete(key);
				}
				status = true;
		}
		return status;
	}
	
	public Folio EditChargeInFolio(long FolioId,String chargeIdString) throws EntityNotFoundException{
		Folio F = GetFolio(FolioId);
		F.setChargeString(chargeIdString);
		Key k = datastore.put(F.getEntity());
		F.setId(k.getId());
		F.setKey(k);

		return F;
	}
	
	public double RoutetoNewFolio(long hotelId,String chargeList, String groupId,long resId,long FolioIdmove) throws EntityNotFoundException
	{
		FolioLogic folioLogic = new FolioLogic(req,resp);
		ReservationLogic resLogic = new ReservationLogic(req,resp);
		ChargeLogic chargeLogic = new ChargeLogic(req,resp);
		String [] chsrgeresItem =chargeList.split(","); 
		for(int i =0;i<chsrgeresItem.length;i++)
		{
			long folioId= 0;
			Charge c = chargeLogic.GetCharge(Long.parseLong(chsrgeresItem[i]));
			folioId=c.getFolioId();	
			if(folioId != 0)
			{
				Folio f = GetFolio(folioId);
			
				String chString=f.getChargeString();
				String[] chArray =chString.trim().split(",");
				StringBuffer result = new StringBuffer();
				//use for delete charge of folio
				for(int n =0;n<chArray.length;n++)
				{
					
						if(!chsrgeresItem[i].trim().equals(chArray[n]) && n == (chArray.length-1))
						{
							result.append( chArray[n] );	
						}
						else if(!chsrgeresItem[i].trim().equals(chArray[n]) && n < (chArray.length-1))
						{
							if(!chsrgeresItem[i].trim().equals(chArray[chArray.length-1]))
							{
								result.append( chArray[n] );
							}else
							{
								result.append( chArray[n]+"," );
							}
							
						}	
					
				}
				if(result.toString() != null)
				{
					f.setChargeString(result.toString());
				}else
				{
					f.setChargeString(null);
				}
				
				Key k = datastore.put(f.getEntity());
				f.setId(k.getId());
				f.setKey(k);
			}
				
			String folioItem =null;
			if(FolioIdmove == 0)
			{
				//use for add charge that you select in to new folio 
				Folio nFolio = new Folio();
				if(nFolio.getChargeString() != null && !nFolio.getChargeString().trim().isEmpty())
				{
					nFolio.setChargeString(nFolio.getChargeString()+","+chsrgeresItem[i]);
				}
				else
				{
					nFolio.setChargeString(chsrgeresItem[i]);
				}
				nFolio.setDisplayId(GetMaxFolioDisplayId(hotelId)+1);
				nFolio.setHotelId(hotelId);
				nFolio.setPaymentString(null);
				Key kf = datastore.put(nFolio.getEntity());
				nFolio.setId(kf.getId());
				nFolio.setKey(kf);
			
				folioItem = String.valueOf(nFolio.getId());
				
			}
			else if(FolioIdmove != 0)
			{
				//use for add charge that you select in to folio 
				Folio nFolio = folioLogic.GetFolio(FolioIdmove);
				if(nFolio.getChargeString() != null && !nFolio.getChargeString().trim().isEmpty())
				{
					nFolio.setChargeString(nFolio.getChargeString()+","+chsrgeresItem[i]);
				}
				else
				{
					nFolio.setChargeString(chsrgeresItem[i]);
						
				}
				nFolio.setHotelId(hotelId);
				Key kf = datastore.put(nFolio.getEntity());
				nFolio.setId(kf.getId());
				nFolio.setKey(kf);
			
				folioItem = String.valueOf(nFolio.getId());
			}
				Charge ch = chargeLogic.GetCharge(Long.parseLong(chsrgeresItem[i]));
				
				ch.setSubFolio(folioItem+"_"+i);
				ch.setFolioId(Long.parseLong(folioItem));
				
				Key kc = datastore.put(ch.getEntity());
				ch.setId(kc.getId());
				ch.setKey(kc);
			
			
				if(resId != 0)
				{
					Reservation res = resLogic.GetReservation(resId);
					if(res.getFolioListString() != null)
					{
						res.setFolioListString(res.getFolioListString()+","+folioItem);
					}else
					{
						res.setFolioListString(folioItem);
					}
					
					Key resk = datastore.put(res.getEntity());
					res.setId(resk.getId());
					res.setKey(resk);
					
					//double b =new FolioLogic().EditCgargeInRes( String.valueOf(res.getId()),"0");
				}
				else if(!groupId.equals("0"))
				{
					Group g = resLogic.GetGroup(Long.parseLong(groupId));
					if(g.getFolioListString() != null)
					{
						g.setFolioListString(g.getFolioListString()+","+folioItem);
					}else
					{
						g.setFolioListString(folioItem);
					}
					
					Key gk = datastore.put(g.getEntity());
					g.setId(gk.getId());
					g.setKey(gk);
					//double b =new FolioLogic().EditCgargeInRes("0",String.valueOf(g.getId()));
				}
	
		}
		
		
		return 1;
	}
	
	public boolean DeleteChargeRoute(String resId,String groupId ,String ChargeId) throws EntityNotFoundException
	{
		ReservationLogic resLogic = new ReservationLogic(req,resp);
		if(!resId.isEmpty()){
			String [] chsrgeresItem =ChargeId.split(","); 
			String [] resIdItem =resId.split(","); 
			Reservation res = new Reservation();
			String otherchAryList ="";
			String chAryList ="";
			for(int i =0;i<chsrgeresItem.length;i++)
			{
				for(int n =0;n<resIdItem.length;n++){
					 res = resLogic.GetReservation(Long.parseLong(resIdItem[n]));
					String [] resChAry = res.getChargeListString().split(",");
					List<String> list=new ArrayList<String>(Arrays.asList(resChAry));
					for(int m=0;m<resChAry.length;m++)
					{
						if(resChAry[m].equals(chsrgeresItem[i])){list.remove(resChAry[m]);}
					}
					
					String[] array = list.toArray(new String[list.size()]);
					if(array != null){
						for(int x=0;x<array.length;x++){
							if(!chAryList.isEmpty()){
								chAryList+=","+array[x];
							}else{
								chAryList =array[x];
							}
						}
					}
					
					String[] resOtherChAry = res.getOtherChargeString().split(",");
					List<String> otherlist=new ArrayList<String>(Arrays.asList(resOtherChAry));
					for(int m=0;m<resOtherChAry.length;m++)
					{
						if(resOtherChAry[m].equals(chsrgeresItem[i])){otherlist.remove(resOtherChAry[m]); }
					}
					
					String[] otherarray = otherlist.toArray(new String[otherlist.size()]);
					if(array != null){
						for(int x=0;x<otherarray.length;x++){
							if(!chAryList.isEmpty()){
								otherchAryList+=","+otherarray[x];
							}else{
								otherchAryList =otherarray[x];
							}
						}
					}
				}
			}
			res.setChargeListString(chAryList);
			res.setOtherChargeString(otherchAryList);
			Key resk = datastore.put(res.getEntity());
			res.setId(resk.getId());
			res.setKey(resk);
		}
		if(!groupId.equals("0"))
		{
			String [] chsrgeresItem =ChargeId.split(","); 
			Group g  = new Group();
			String chAryList="";
			String otherchAryList="";
			for(int i =0;i<chsrgeresItem.length;i++)
			{
				 g = resLogic.GetGroup(Long.parseLong(groupId));
				String [] resChAry = g.getChargeListString().split(",");
				List<String> list=new ArrayList<String>(Arrays.asList(resChAry));
				for(int m=0;m<resChAry.length;m++)
				{
					if(resChAry[m].equals(chsrgeresItem[i])){list.remove(resChAry[m]);}
				}
				String[] array = list.toArray(new String[list.size()]);
				if(array != null){
					for(int x=0;x<array.length;x++){
						if(!chAryList.isEmpty()){
							chAryList+=","+array[x];
						}else{
							chAryList =array[x];
						}
					}
				}

				String[]resOtherChAry = g.getOtherChargeString().split(",");
				List<String> otherlist=new ArrayList<String>(Arrays.asList(resOtherChAry));
				for(int m=0;m<resOtherChAry.length;m++)
				{
					if(resOtherChAry[m].equals(chsrgeresItem[i])){
						otherlist.remove(resOtherChAry[m]); 
						}
				}
				String[] otherarray = otherlist.toArray(new String[list.size()]);
				if(array != null){
					for(int x=0;x<otherarray.length;x++){
						if(!chAryList.isEmpty()){
							otherchAryList+=","+otherarray[x];
						}else{
							otherchAryList =otherarray[x];
						}
					}
				}
			}
			g.setChargeListString( chAryList);
			g.setOtherChargeString(otherchAryList);
		}
		return true;
		
		
	}
	
	public double EditCgargeInRes(String resId,String chargeGroupId) throws EntityNotFoundException
	{
		ReservationLogic resLogic = new ReservationLogic(req,resp);
		FolioLogic folioLogic = new FolioLogic(req,resp);
		ChargeLogic chargeLogic = new ChargeLogic(req,resp);
		String [] n=resId.split(",");
		
				if(resId !=null && resId !="0")
				{
					for(int i =0;i<n.length;i++)
					{
						if(!n[i].equals("0")){
						Reservation res = resLogic.GetReservation(Long.parseLong(n[i]));
						
						String[] folioStringList = res.getFolioListString().split(",");
						List<String> chargeRoomRate=new ArrayList<String>();
						List<String> chargeOther=new ArrayList<String>();
						for(int h = 0;h<folioStringList.length;h++)
						{
							
							Folio foo = folioLogic.GetFolio(Long.parseLong(folioStringList[h].trim()));
							if(foo.getChargeString().isEmpty()){continue;}
							String[]chargeFolio =foo.getChargeString().split(",");
							
								for(int a= 0;a<chargeFolio.length;a++)
								{
									if(chargeFolio[a].isEmpty()){
										break;
									}
									Charge c = chargeLogic.GetCharge(Long.parseLong(chargeFolio[a]));
									if(c.isRoomCharge())
									{
										
										chargeRoomRate.add(chargeFolio[a]);
									}else
									{
										
										chargeOther.add(chargeFolio[a]);
									}
								}
							
						}
						String chargeText=getInFolioChargeList(res.getChargeListString(),chargeRoomRate);
						res.setChargeListString(chargeText);
						String otherchargeText=getInFolioChargeList(res.getOtherChargeString(),chargeOther);
						res.setOtherChargeString(otherchargeText);
						Key kk = datastore.put(res.getEntity());
						res.setId(kk.getId());
						res.setKey(kk);
									}
						}
			}
				
				if(!chargeGroupId.equals("0"))
				{
					Group g= resLogic.GetGroup(Long.parseLong(chargeGroupId));
					String[] folioStringList = g.getFolioListString().split(",");
					List<String> chargeRoomRate=new ArrayList<String>();
					List<String> chargeOther=new ArrayList<String>();
					for(int h = 0;h<folioStringList.length;h++)
					{
						Folio foo = folioLogic.GetFolio(Long.parseLong(folioStringList[h].trim()));
					
						String[]chargeFolio =foo.getChargeString().split(",");
							for(int a= 0;a<chargeFolio.length;a++)
							{
								if(chargeFolio[a].isEmpty()){
									break;
								}
								Charge c = chargeLogic.GetCharge(Long.parseLong(chargeFolio[a]));
								if(c.isRoomCharge())
								{
									chargeRoomRate.add(chargeFolio[a]);
								}else
								{
									chargeOther.add(chargeFolio[a]);
								}
							}
					
					}
					String chargeText=getInFolioChargeList(g.getChargeListString(),chargeRoomRate);
					g.setChargeListString(chargeText);
					String otherchargeText=getInFolioChargeList(g.getOtherChargeString(),chargeOther);
					g.setOtherChargeString(otherchargeText);
					Key kk = datastore.put(g.getEntity());
					g.setId(kk.getId());
					g.setKey(kk);
				}
		return 1;
	}

	public String getInFolioChargeList(String resCharge,List<String>folioStringList)
	{
		String result="";
		if(resCharge.isEmpty()){resCharge =null;}
		String chAryList ="";
		if(resCharge == null&&folioStringList.size()==0){
			return result;
		}else if(resCharge != null&&folioStringList.size()==0){
			return resCharge;
		}else if(resCharge == null&&folioStringList.size()!=0){
			String[] array = folioStringList.toArray(new String[folioStringList.size()]);
			
				for(int x=0;x<array.length;x++){
					if(!chAryList.isEmpty()){
						chAryList+=","+array[x];
					}else{
						chAryList =array[x];
					}
				}
			
			return chAryList;
		}
		String [] chargeResAry = resCharge.trim().split(",");
		for(int y= 0;y<chargeResAry.length;y++)
		{	
			String chIdString =isInFolio(chargeResAry[y],folioStringList);
				if(chIdString!=null){
					if(!result.equals(""))
					{
						result +=chIdString;
					}else
					{
						String[]a=chIdString.split(",");
						result +=a[1];
					}	
				}
		}
		return result;
	}

	public String isInFolio(String resId,List<String>folioChageList)
	{
		String chargeIdString = null;
		for(String s:folioChageList)
		{
			if(resId.equals(s))
			{
				chargeIdString= null;	
			} 	
			else
			{
				chargeIdString = ","+s;
			}
		}
		return chargeIdString;
		
	}
	public Folio UpdateFolio(Folio c)
	{
		Key key = datastore.put(c.getEntity());
		c.setId(key.getId());
		c.setKey(key);
		return c;
	}
	public HashMap<String,String>  Lockfolio(long folioId) throws EntityNotFoundException{
		Folio f = new FolioLogic(req,resp).GetFolio(folioId);
		SubPaymentLogic subPaymentLogic = new SubPaymentLogic(req,resp);
		if( f.getPaymentString() == null){return null;}
		double charge =0; 
		double payment=0;
		for(Charge ch:f.getCharge()){
			charge+=ch.getChargeAmount();
		}
		String [] paymentAry = f.getPaymentString().split(",");
		for(int i =0;i<paymentAry.length;i++){
			SubPayment sp = subPaymentLogic.GetSubPayment(Long.parseLong(paymentAry[i]));
			payment +=sp.getAmount();
		}
		if(charge-payment == 0){
			for(Charge c:f.getCharge()){
				c.setLock(true);
				Key kk = datastore.put(c.getEntity());
				c.setId(kk.getId());
				c.setKey(kk);
			}	
			f.setLock(true);
			Key kk = datastore.put(f.getEntity());
			f.setId(kk.getId());
			f.setKey(kk);
			HashMap<String,String> returnValue = new HashMap<String,String>();
			returnValue.put("folioId",String.valueOf(folioId));
			returnValue.put("chargeListId", f.getChargeString());
			return returnValue;
		}else{
			return null;
		}
			
	}
	
	public long GetMaxFolioDisplayId(long hotelId)
	{
		Query q = new Query(EntityName.Folio);

		Filter filterHotel = new FilterPredicate("hotelId",
				FilterOperator.EQUAL, hotelId);
		q.setFilter(filterHotel).addSort("displayId", SortDirection.DESCENDING);

		List<Folio> list = GetList(datastore.prepare(q).asList(FetchOptions.Builder.withLimit(1)));
		if(list.size()>0)
			return list.get(0).getDisplayId();
		return 0;
	}
}

